<template>
  <div class="divWarehouse divCheckList">
    <div class="divHead box">
      <div>
        <el-row :gutter="30">
          <el-col :span="6">
            <div class="divLable">盘点单号</div>
            <el-input
              placeholder="请输入"
              v-model="searchParams.code"
            />
          </el-col>
          <el-col :span="6">
            <div class="divLable">盘点状态</div>
            <el-select
              v-model="searchParams.status"
              clearable
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in checkStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <div class="divLable">盘点类型</div>
            <el-select
              v-model="searchParams.type"
              clearable
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in checkTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <div class="textRight">
              <base-button
                class="minorImportantButton btnSearch"
                @click="btnSearchClick"
              >搜索</base-button>
              <base-button class="unimportanceButton" @click="btnResetClick">重置</base-button>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="30" style="margin-top:21px">
          <el-col :span="6">
            <div class="divLable">货主</div>
            <el-select
              v-model="searchParams.ownerId"
              clearable
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in ownerOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <div class="divLable">盘点库区</div>
              <el-cascader  v-model="location"
                            @change="handleItemChange"
                            :props="cascaderOptions.props"
                            clearable
                            style="width:100%"
              >
              </el-cascader>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="divContent box">
      <div class="tableInfo">
        <base-button
          class="importantButton"
          @click="btnAddClick"
        >新增盘点单</base-button>
        <base-button
          class="unimportanceButton"
          @click="btnBatchAddCheckTask([])"
        >生成盘点任务</base-button>
      </div>
      <div  v-if="tableData.length>0">
        <el-table
          :data="tableData"
          stripe
          border
          ref="table"
          style="width: 100%"
          v-loading="loading"
          :header-cell-style="{ background: '#f9f6ee' }"
           @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            type="index"
            align="center"
            width="68"
            label="序号"
          />
          <el-table-column
            prop="code"
            align="center"
            label="盘点单号"
            width="160"
          />
          <el-table-column
            prop="ownerName"
            align="center"
            label="货主"
            width="150"
          />
          <el-table-column
            prop="status"
            align="center"
            label="盘点单状态"
            width="160"
            :filters="[{text: '新建', value: 1}, {text: '一盘中', value: 2}, {text: '一盘完成', value: 3},{text: '复盘中', value: 4},{text: '复盘完成', value: 5},{text: '已取消', value: 6}]"
            :filter-method="filterHandler"
          >
            <template slot-scope="{row}">
              <span v-if="row.status === 1">新建</span>
              <span v-if="row.status === 2">一盘中</span>
              <span v-if="row.status === 3">一盘完成</span>
              <span v-if="row.status === 4">复盘中</span>
              <span v-if="row.status === 5">复盘完成</span>
              <span v-if="row.status === 6">已取消</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            align="center"
            label="创建时间"
            width="200"
            sortable
          />
          <el-table-column
            prop="planCheckTime"
            align="center"
            label="计划盘点时间"
            width="160"
            sortable
          />
          <el-table-column
            prop="reason"
            align="center"
            label="盘点原因"
            width="160"
            :filters="[{text: '规划', value: 'GH'}, {text: '货主', value: 'HZ'}, {text: '差异', value: 'CY'}]"
            :filter-method="filterHandler"
          >
            <template slot-scope="{row}">
              <span v-if="row.reason === 'GH'">规划</span>
              <span v-if="row.reason === 'HZ'">货主</span>
              <span v-if="row.reason === 'CY'">差异</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="dimension"
            align="center"
            label="盘点维度"
            width="160"
            :filters="[{text: '库位', value: 'KW'}, {text: '货品', value: 'HP'}]"
            :filter-method="filterHandler"
          >
            <template slot-scope="{row}">
              <span v-if="row.dimension === 'KW'">库位</span>
              <span v-if="row.dimension === 'HP'">货品</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="type"
            align="center"
            label="盘点类型"
            width="160"
            :filters="[{text: '随机盘点', value: 'SJPD'}, {text: '计划盘点', value: 'JHPD'}]"
            :filter-method="filterHandler"
          >
            <template slot-scope="{row}">
              <span v-if="row.type === 'SJPD'">随机盘点</span>
              <span v-if="row.type === 'JHPD'">计划盘点</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="warehouseName"
            align="center"
            label="盘点仓库"
            width="160"
          >
          </el-table-column>
          <el-table-column
            prop="areaName"
            align="center"
            label="盘点库区"
            width="150"
          >
          </el-table-column>
          <el-table-column
            prop="createName"
            align="center"
            label="创建人"
            width="160"
          />
          <el-table-column label="操作" align="center" width="250" fixed="right">
            <template slot-scope="{row}">
              <base-button class="fontOperateButton" v-if="row.status === 1" @click="editClick(row.id)">修改详情</base-button>
              <base-button class="fontOperateButton" v-if="row.status === 1"  @click="btnBatchAddCheckTask([row.id])">生成盘点任务</base-button>
              <base-button class="fontOperateButton" v-if="row.status === 1" @click="btnCancleClick(row.id,row.code)">取消</base-button>
              <base-button class="fontOperateButton" v-if="row.status !== 1" @click="detailClick(row.id)">查看详情</base-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
      <base-pagination :total="paging.total" :limit="paging.size" @current-change="handleCurrentChange"  @size-change="handleSizeChange"></base-pagination>
      </div>
      <div
        v-else
        class="emptyTip"
      >
        <span class="imgIcon"></span>
        <p>暂无盘点单</p>
      </div>
      <el-dialog
        :title="dialogData.dialogTitle"
        :visible.sync="dialogData.visible"
        width="30%">
        <span>{{dialogData.msg}}</span>
        <span slot="footer" class="dialog-footer">
          <base-button class="unimportanceButton btnCancle" @click="dialogData.visible = false">取 消</base-button>
          <base-button class="minorImportantButton" type="primary" @click="dialogSure">确 定</base-button>
        </span>
      </el-dialog>
      <base-list-dialog :visible="batchDialogData.visible"
                        :title="batchDialogData.title"
                        :subTitle="batchDialogData.subTitle"
                        :msg="batchDialogData.msg"
                        :itemList="batchDialogData.itemList"
                        :msgFailure="batchDialogData.msgFailure"
                        :itemListFailure="batchDialogData.itemListFailure"
                        @btn-sure-click="btnSureClick"
                        >
      </base-list-dialog>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import BaseButton from '@/components/base-button/index.vue'
import BasePagination from '@/components/base-pagination/index.vue'
import {
  changeLocationStatus
} from '@/module-base/api/location'
import { checkStatusOptions, checkTypeOptions } from '@/utils/common-select-data'
import { ICommonReturn, ICommonSelectOptions, ICommonSelectOptionsString } from '@/utils/common-interface'
import { getAllWarehouse } from '@/module-base/api/warehouse'
import { IWarehouseTableData } from '@/module-base/interface/warehouse'
import { getAllAreaList } from '@/module-base/api/area'
import { IAreaTableData } from '@/module-base/interface/area'
import { getAllOwner } from '@/module-business/api/owner'
import { IOwnerTableData } from '@/module-business/interface/owner'
import { cancleCheck, generateCheckTask, getCheckDetailPaging } from '@/module-storage/api/check'
import { ICheckTableData } from '@/module-storage/interface/check'
import BaseListDialog from '@/components/base-dialog/index1.vue'

@Component({
  name: 'CheckList',
  components: {
    BaseButton,
    BasePagination,
    BaseListDialog
  }
})

export default class extends Vue {
  private tableData: ICheckTableData[] = []
  private checkStatusOptions:ICommonSelectOptions[] = []
  private checkTypeOptions:ICommonSelectOptionsString[] = []
  private ownerOptions:ICommonSelectOptions[] = []
  private cascaderOptions = {
    props: {
      lazy: true,
      lazyLoad: async(node:any, resolve:any) => { // 使用箭头函数来在函数中使用页面的this
        const { level } = node
        if (level === 0) {
          const { data } = await getAllWarehouse({ status: 1 })
          const nodes = data.map((item:IWarehouseTableData) => {
            return {
              value: item.id,
              label: item.name,
              leaf: level >= 1 // 不设置的话点击第一级菜单也会触发change事件  文本区域也会填充
            }
          })
          resolve(nodes)
        } else if (level === 1) {
          const { data } = await getAllAreaList({ warehouseId: node.value, status: 1 })
          let nodes = []
          if (data) {
            nodes = data.map((item:IAreaTableData) => {
              return {
                value: item.id,
                label: item.name,
                leaf: level >= 1// 不设置的话还会继续加载下一级菜单
              }
            })
          }
          resolve(nodes)
        }
      }
    }
  }

  private loading = false
  private searchParams = {
    code: '',
    status: undefined,
    type: undefined,
    ownerId: undefined,
    areaId: undefined
  }

  private location = []

  private dialogData ={
    id: '',
    msg: '',
    status: -1,
    dialogTitle: '',
    visible: false
  }

  private batchDialogData = {
    ids: [] as number[],
    title: '',
    subTitle: '',
    msg: '',
    itemList: [] as string[],
    visible: false,
    msgFailure: '',
    itemListFailure: [] as string[]
  }

  private dialogFileImportData = {
    updatedTitle: '库位',
    isFileVisible: false,
    uploadUrl: '/api/location/upload'
  }

  private paging = {
    current: 1, // 当前页码
    size: 10, // 每页数据量
    total: 0
  }

  @Watch('$route', { immediate: true })
  private onRouteChange() {
    this.getList()
    this.getOwnerOptions()
  }

  mounted() {
    this.checkStatusOptions = checkStatusOptions
    this.checkTypeOptions = checkTypeOptions
  }

  private async getOwnerOptions() {
    const { data } = await getAllOwner(null)
    this.ownerOptions = data.map((item:IOwnerTableData) => {
      return {
        label: item.name,
        value: item.id
      }
    })
  }

  private handleItemChange(value:string) {
    if (Array.isArray(value) && value.length === 2) {
      this.searchParams.areaId = value[1]
    }
  }

  private btnSearchClick() {
    this.getList()
  }

  private btnResetClick() {
    this.searchParams = {
      code: '',
      status: undefined,
      type: undefined,
      ownerId: undefined,
      areaId: undefined
    }
    this.location = []
    this.getList()
  }

  private btnAddClick() {
    this.$router.push({ path: 'list/details/null' })
  }

  private getParams() {
    const current = this.paging.current
    const size = this.paging.size
    const params = {
      ...this.searchParams,
      current,
      size
    }
    if (params.status === '') {
      delete params.status
    }
    if (params.type === '') {
      delete params.type
    }
    if (params.ownerId === '') {
      delete params.ownerId
    }
    if (this.location.length < 2) {
      delete params.areaId
    }
    return params
  }

  private async getList() {
    this.loading = true
    const params = this.getParams()
    const { data } = await getCheckDetailPaging(params)
    this.loading = false
    this.tableData = data.records
    this.paging.total = parseInt(data.total, 10)
  }

  private editClick(id:string) {
    this.$router.push({ path: `list/details/${id}` })
  }

  private detailClick(id:string) {
    this.$router.push({
      path: `list/list-detail/${id}`
    })
  }

  private btnCancleClick(id:string, code:string) {
    this.dialogData.msg = `确定要取消盘点单号为为：${code} 的盘点单吗？`
    this.dialogData.id = id
    this.dialogData.visible = true
    this.dialogData.dialogTitle = '确认取消'
  }

  private async cancleSure() {
    const params = {
      id: this.dialogData.id
    }
    const data = await cancleCheck(params) as unknown as ICommonReturn
    if (data.code === 0) {
      this.$message({
        showClose: true,
        message: '取消成功',
        type: 'success'
      })
      this.dialogData.visible = false
      this.getList()
      this.batchDialogData.ids = []
    } else {
      this.$message({
        showClose: true,
        message: data.msg,
        type: 'error'
      })
    }
  }

  private dialogSure() {
    if (this.dialogData.msg.indexOf('取消') > 0) {
      this.cancleSure()
    } else {
      this.statusChangeSure()
    }
  }

  private statusChangeClick(status:number, id:string, name:string) {
    const type = status === 0 ? '启用' : '停用'
    this.dialogData = {
      msg: `确定要${type}仓库名为：${name} 的仓库吗？`,
      id: id,
      status: status === 0 ? 1 : 0,
      visible: true,
      dialogTitle: `确认${type}`
    }
  }

  private async statusChangeSure() {
    const params = {
      id: this.dialogData.id,
      status: this.dialogData.status
    }
    const data = await changeLocationStatus(params) as unknown as ICommonReturn
    if (data.code === 0) {
      this.$message({
        showClose: true,
        message: '状态改变成功',
        type: 'success'
      })
      this.dialogData.visible = false
      this.getList()
    } else {
      this.$message({
        showClose: true,
        message: data.msg,
        type: 'error'
      })
    }
  }

  private handleCurrentChange(page:number) {
    this.paging.current = page
    this.getList()
  }

  private handleSizeChange(page:number) {
    this.paging.size = page
    this.paging.current = 1
    this.getList()
  }

  private handleSelectionChange(items:ICheckTableData[]) {
    this.batchDialogData.ids = items.map(item => {
      return item.id
    })
  }

  private filterHandler(value:any, row:any, column:any) {
    const property = column.property
    return row[property] === value
  }

  private async btnBatchAddCheckTask(ids:number[]) {
    if (ids.length > 0) { // 编辑
      this.batchDialogData.ids = ids
    }
    const batchDialogData = this.batchDialogData
    if (batchDialogData.ids.length === 0) {
      this.$message.error('请选择盘点单')
    } else {
      this.batchDialogData = {
        ids: [] as number[],
        title: '盘点任务生成',
        subTitle: '',
        msg: '',
        itemList: [] as string[],
        visible: false,
        msgFailure: '',
        itemListFailure: [] as string[]
      }
      const { data } = await generateCheckTask(batchDialogData.ids)
      const errors = data.errors as string[]
      const results = data.results as string[]
      if (results.length > 0) {
        this.batchDialogData.msg = '盘点任务编号如下，请在盘点任务中查看'
        this.batchDialogData.itemList = results
        this.batchDialogData.subTitle = results.length + '个盘点任务生成成功！'
      }

      if (errors.length > 0) {
        this.batchDialogData.msgFailure = '盘点任务生成失败原因如下'
        this.batchDialogData.itemListFailure = errors
        this.batchDialogData.subTitle += (errors.length + '个盘点任务生成失败！')
      }
      this.batchDialogData.visible = true
      this.getList()
    }
    (this.$refs.table as any).clearSelection()
  }

  private btnSureClick() {
    this.batchDialogData.visible = false
  }
}
</script>
<style lang="scss" scoped>
.divCheckList{
  .divHead{
    height: auto;
  }
}
</style>
